/**
 * 粉色风格确认对话框工具
 */

import { createApp, h } from 'vue'
import ConfirmModal from '../components/ConfirmModal.vue'

let modalInstance = null
let modalContainer = null

/**
 * 显示确认对话框
 * @param {Object} options - 配置选项
 * @param {String} options.title - 标题
 * @param {String} options.message - 消息内容
 * @returns {Promise<boolean>} - 用户确认返回true，取消返回false
 */
export function showConfirm(options = {}) {
  return new Promise((resolve) => {
    // 如果已经有实例，先销毁
    if (modalInstance) {
      hideConfirm()
    }

    // 创建容器
    modalContainer = document.createElement('div')
    document.body.appendChild(modalContainer)

    // 默认配置
    const defaultOptions = {
      title: '确认操作',
      message: '确定要执行此操作吗？'
    }

    const finalOptions = { ...defaultOptions, ...options }

    // 创建组件实例
    modalInstance = createApp({
      data() {
        return {
          show: true
        }
      },
      methods: {
        handleConfirm() {
          this.show = false
          setTimeout(() => {
            hideConfirm()
            resolve(true)
          }, 300)
        },
        handleCancel() {
          this.show = false
          setTimeout(() => {
            hideConfirm()
            resolve(false)
          }, 300)
        }
      },
      render() {
        return h(ConfirmModal, {
          modelValue: this.show,
          title: finalOptions.title,
          message: finalOptions.message,
          'onUpdate:modelValue': (val) => {
            this.show = val
          },
          onConfirm: this.handleConfirm,
          onCancel: this.handleCancel
        })
      }
    })

    modalInstance.mount(modalContainer)
  })
}

/**
 * 隐藏确认对话框
 */
export function hideConfirm() {
  if (modalInstance) {
    modalInstance.unmount()
    modalInstance = null
  }
  
  if (modalContainer && modalContainer.parentNode) {
    modalContainer.parentNode.removeChild(modalContainer)
    modalContainer = null
  }
}

export default {
  show: showConfirm,
  hide: hideConfirm
}
